#pragma once

#include <iostream>
#include <string>
#include <thread>
#include <functional>
#include <unordered_map>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include "Socket.hpp"
#include "commen.hpp"
#include "Log.hpp"

const int default_socket_fd = -1;
const int retry_chance = 5;

class TcpSocket : public Socket
{
public:
    TcpSocket(int socket_fd = default_socket_fd) 
        : _socket_fd(socket_fd)
    {}

    void create() override
    {
        _socket_fd = ::socket(AF_INET, SOCK_STREAM, 0);
        if(_socket_fd < 0)
        {
            log.message(FATAL, "socket error, %d: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        int opt = 1; //选项
        setsockopt(_socket_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)); //地址复用
        log.message(INFO, "socket success, socket fd: %d", _socket_fd);
    }

    void bind(uint16_t port) override
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(::bind(_socket_fd, (struct sockaddr*)&local, sizeof(local)) != 0)
        {
            log.message(FATAL, "bind error, %d: %s\n", errno, strerror(errno));
            exit(BIND_ERR);
        }
        log.message(INFO, "bind success...");
    }

    void listen(int backlog) override
    {
        if(::listen(_socket_fd, backlog) != 0)
        {
            log.message(FATAL, "listen error, %d: %s\n", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
        log.message(INFO, "listen success...");
    }

    Socket* accept(std::string* peerIp, uint16_t* peerPort) override
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int communi_fd = ::accept(_socket_fd, (struct sockaddr*)&peer, &len);
        if(communi_fd < 0)
        {
            log.message(WARN, "accept socket error, %d: %s, accept continue...", errno, strerror(errno));
            return nullptr;
        }

        char buffer[64];
        inet_ntop(AF_INET, &peer.sin_addr, buffer, sizeof(buffer));
        *peerIp = buffer;
        *peerPort = ntohs(peer.sin_port);

        log.message(INFO, "accept success...");
        return new TcpSocket(communi_fd);
    }

    void connect(std::string& serverIp, uint16_t serverPort) override
    {
        if(tryConnect(serverIp, serverPort) == false)
        {
            exit(CONNECT_ERR);
        }
    }

    int getSocketFd() override
    {
        return _socket_fd;
    }

    void setSocketFd(int socketFd) override
    {
        _socket_fd = socketFd;
    }

    ~TcpSocket() 
    {
        close(_socket_fd);
    }
public:
    bool tryConnect(std::string& serverIp, uint16_t serverPort)
    {
        if(getConnection(serverIp, serverPort) == false)
        {
            int cnt = retry_chance;
            while(cnt != 0)
            {
                sleep(1);
                log.message(INFO, "server status is unknown, try reconnecting: %d...", cnt);
                if(getConnection(serverIp, serverPort) == true)
                {
                    return true;
                }
                cnt--;
            }
            log.message(ERROR, "server offline, write error...");
            return false;
        }
        return true;
    }

    bool getConnection(std::string& serverIp, uint16_t serverPort)
    {
        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(serverPort);
        inet_pton(AF_INET, serverIp.c_str(), &server.sin_addr);

        int n = ::connect(_socket_fd, (struct sockaddr*)&server, sizeof(server));
        if(n < 0)
        {
            log.message(ERROR, "connect error, %d: %s", errno, strerror(errno));
            return false;
        }
        log.message(INFO, "connect success...");
        return true;
    }
private:
    int _socket_fd;
};